package cn.com.acca.ma.test;

class TicketsSystem{
	public static void main(String[] args){
	   	SellThread st=new SellThread();
	   	new Thread(st).start(); //由于时间片的关系，main()方法所在线程时间片没有到期，所以此调用并没有运行
	   	try{
	    	Thread.sleep(1);
	   	}catch(Exception e){
	    	e.printStackTrace();
	   	}
	   	st.b=true;
	   	new Thread(st).start();
	}
}

class SellThread implements Runnable{
	int tickets=100;
	Object obj=new Object();
	boolean b=false;
	public void run(){
	   	if(b==false){
	    	while(true)
	     		sell();
	   	}else{
	    	while(true){
	     		synchronized(this){
	      			if(tickets>0){
	       				try{
	        				Thread.sleep(10);
	       				}catch(Exception e){
	        				e.printStackTrace();
	       				}
	       				System.out.println(Thread.currentThread().getName()+" sell tickets:"+tickets);
	       				tickets--;
	      			}
	     		}
	    	}
	   	}
	}
	public synchronized void sell(){
	   	if(tickets>0){
	    	try{
	     		Thread.sleep(10);
	    	}catch(Exception e){
	     		e.printStackTrace();
	    	}
	    	System.out.println(Thread.currentThread().getName()+" sell tickets:"+tickets);
	    	tickets--;
	   	}
	}
}
